package com.finance.cooperate.data.thread;

import com.finance.cooperate.common.constant.Constant;
import com.finance.cooperate.common.properties.CooperateProperties;
import com.finance.cooperate.common.utils.CSVUtils;
import com.finance.cooperate.common.utils.SpringContextUtil;
import com.finance.cooperate.data.feature.FeatureAllSet;
import com.finance.cooperate.data.feature.FeatureDefinition;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName ReaderProcessorThread
 * @Description Reader处理线程
 * @Author shen
 * @Date 2023/8/10 21:21
 * @Modify ...
 */
public class ReaderProcessorThread implements Runnable{


    @Override
    public void run() {

        CooperateProperties crmProperties = (CooperateProperties) SpringContextUtil
                .getApplicationContext().getBean("cooperateProperties");

        ReaderQueue queue = ReaderQueue.getInstance();

        while (true) {
            try {

                List<Map<String, String>> list = queue.drainTo();
                for (Map<String, String> model: list) {


                    List resultList = new ArrayList();
                    Map<String, String> rowMap = new HashMap<>();
                    Map<String, String> keyMap = new HashMap<>();

                    // 所有的输出特征
                    Map<String, String> allFeature = FeatureAllSet.modelFeature;

                    for (String key : allFeature.keySet()) {

                        //特征停用
                        if (!FeatureDefinition.getStatus(allFeature.get(key))) {
                            continue;
                        }

                        String value = model.get(key);
                        if (value == null || value.isEmpty() || value.equals("null")){

                            // 如果是热编码特征，则输出为0
                            if (FeatureDefinition.isOneHot(allFeature.get(key))) {
                                value = String.valueOf(Constant.IS_NO_HIT);
                            } else {
                                value = String.valueOf(Constant.MISSING_VALUE);
                            }

                        }

                        rowMap.put(key, value);
                        // 后面可能调整
                        keyMap.put(key, key);

                    }

                    resultList.add(rowMap);

                    CSVUtils.createCSVFile(resultList,
                            keyMap,
                            crmProperties.getEnvironment().getFeatureCsvFilePath(),
                            crmProperties.getEnvironment().getFeatureCsvFileName());

                }

            } catch (Exception e) {
                e.printStackTrace();
            }

        }

    }
}
